package com.ssy.lingxi.workflow.serviceimpl;

import com.ssy.lingxi.workflow.entity.ExternalTaskDefinition;
import com.ssy.lingxi.workflow.entity.InternalTaskDefinition;
import com.ssy.lingxi.workflow.repository.InternalTaskRepository;
import com.ssy.lingxi.workflow.service.IExternalTaskDaoService;
import com.ssy.lingxi.workflow.service.IInternalTaskDaoService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 内部任务Dao接口实现类型，使用了外部任务的Redis缓存
 * @author 万宁
 * @version 2.0.0
 * @date 2021-04-27
 */
@Service
public class InternalTaskDaoServiceImpl implements IInternalTaskDaoService {
    @Resource
    private IExternalTaskDaoService externalTaskDaoService;

    @Resource
    private InternalTaskRepository internalTaskRepository;

    /**
     * 查找内部任务
     *
     * @param processKey 流程Key
     * @param taskName   任务名称
     * @param taskType   任务类型
     * @return 内部任务定义
     */
    @Override
    public List<InternalTaskDefinition> findByProcessKeyAndTaskNameAndTaskType(String processKey, String taskName, Integer taskType) {
        List<ExternalTaskDefinition> externalTaskDefinitions = externalTaskDaoService.findByProcessKey(processKey);
        if(!CollectionUtils.isEmpty(externalTaskDefinitions)) {
            return externalTaskDefinitions.stream().flatMap(externalTask -> externalTask.getSubTasks().stream()).filter(internalTask -> internalTask.getTaskName().equals(taskName) && internalTask.getTaskType().equals(taskType)).collect(Collectors.toList());
        }

        return internalTaskRepository.findByProcessKeyAndTaskNameAndTaskType(processKey, taskName, taskType);
    }
}
